import { createRouter, createWebHashHistory } from "vue-router";
import routes from "../router/defaultRoutes";
import { generateRouter } from "../utils/index";
import { useUserStore } from "../store/layout";
import { sysMenu } from "@/api/userManagement";
import {getMenuCodes,filterByType,filterByName} from '../utils/index'

enum ELOGINSTATE {
  ISLOGIN = "login",
}



const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
const whilelist = ["/login"];

router.beforeEach(async (to: any, from, next) => {

  let user = useUserStore();
  if (!router.hasRoute(to.name)) {
    //  判断是否有该路由
    let userinfo =localStorage.getItem('userInfo')
    
    let { data } = await sysMenu({
      linkSystem: "xinfa",
      account:userinfo
    });
    // 权限按钮
    let button = getMenuCodes(data.data)
    // 所有的按钮
    user.ButtonPermission = button
  let infomnmu = filterByType(data.data,1)
  infomnmu = filterByName(infomnmu)
    user.setUserRouters(infomnmu);
    
    let res = generateRouter(infomnmu);
    user.routes = res;
    //  发生请求得到动态路由，如果没有权限打回登录页面
    res.push({
      path: "/:pathMatch(.*)*",
      name: "404",
      component: () => import("../views/sys/notFound.vue"),
      children: [],
    });
    
    res.forEach((v:any) => {
      router.addRoute(v);
    });
    //  渲染菜单栏
    next({ path: to.fullPath, replace: true });
    // return to.fullPath
    return;
  }
  // 跳转到首页
  if (to.path == "/" || to.path == "") {
    next("/index/home"); // 将"/home"替换为你的首页路径
    return;
  } 
  // 检查是否已登录
  if (localStorage.getItem("token")) {
    if (to.name === "登录") {
      next("/index/home");
    } else {
      next();
    }
  } else if (to.name !== "登录") {
    next("/login");
  } else {
    next();
  }
});

export default router;

